import { ipcRenderer, contextBridge, webUtils } from "electron";
import { AppConfig } from "./types";

contextBridge.exposeInMainWorld("electronAPI", {
  startChat: (data: CreateChatProps) => ipcRenderer.send("start-chat", data),
  onUpdateMessage: (callback: OnUpdatedCallback) =>
    ipcRenderer.on("update-message", (_event, value) => callback(value)),
  // 获取配置
  getConfig: () => ipcRenderer.invoke("get-config"),
  // 更新配置
  updateConfig: (config: Partial<AppConfig>) =>
    ipcRenderer.invoke("update-config", config),
  onMenuNewConversation: (callback: () => void) =>
    ipcRenderer.on("menu-new-conversation", () => callback()),
  onMenuOpenSettings: (callback: () => void) =>
    ipcRenderer.on("menu-open-settings", () => callback()),
  // 显示右键菜单
  showContextMenu: (id: number) => ipcRenderer.send("show-context-menu", id),
  // 删除会话
  onDeleteConversation: (callback: (id: number) => void) =>
    ipcRenderer.on("delete-conversation", (_event, id) => callback(id)),
  // 拷贝图片到本地用户目录
  copyImageToUserDir: (sourcePath: string) =>
    ipcRenderer.invoke("copy-image-to-user-dir", sourcePath),
  getFilePath: (file: File) => webUtils.getPathForFile(file),
});

interface CreateChatProps {
  messages: {
    role: string;
    content: string;
    imagePath?: string;
  }[];
  providerName: string;
  selectedModel: string;
  messageId: number;
}

interface UpdatgedStreamData {
  messageId: number;
  data: {
    is_end: boolean;
    result: string;
    is_error?: boolean;
  };
}

type OnUpdatedCallback = (data: UpdatgedStreamData) => void;
